package com.deam.scorpio.ui.activity;

import android.content.Context;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseViewHolder;
import com.deam.imsdk.elem.BaseElem;
import com.deam.imsdk.elem.IMTextElem;
import com.deam.imsdk.imsdk.ConnectStateListener;
import com.deam.imsdk.imsdk.IMManager;
import com.deam.imsdk.imsdk.MessageListener;
import com.deam.imsdk.imsdk.MiPushClient;
import com.deam.imsdk.net.TCPClient;
import com.deam.imsdk.utils.Constants;
import com.deam.scorpio.R;
import com.qbkj.base_lib.adapter.QuickAdapter;
import com.qbkj.base_lib.layoutmanager.SmoothScrollLayoutManager;
import com.qbkj.base_lib.ui.BaseActivity;

import java.util.ArrayList;
import java.util.List;

public class MessageActivity extends BaseActivity implements MessageListener, ConnectStateListener {
    private String mUserId;
    private String mNetname;
    private QuickAdapter adapter;
    private ArrayList<BaseElem> datas = new ArrayList<>();
    private RecyclerView mRecyclerView;
    private SmoothScrollLayoutManager mLayoutManager;

    @Override
    protected int setContentLayoutId() {
        return R.layout.activity_message;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        mUserId = getIntent().getStringExtra("user_id");
        mNetname = getIntent().getStringExtra("netname");
        v.setText(R.id.title_text, mNetname);
        v.setOnClickListener(this, R.id.send_btn);
        initAdapter();
        IMManager.getInstance().registerMessageListener(mUserId, this);
        IMManager.getInstance().registermConnectState(this);
    }

    private void initAdapter() {
        adapter = new QuickAdapter<BaseElem, BaseViewHolder>(R.layout.item_message, datas) {
            @Override
            public void onBindViewHolder(BaseViewHolder holder, int position) {
                super.onBindViewHolder(holder, position);

            }

            @Override
            protected void convert(BaseViewHolder helper, BaseElem item) {
                super.convert(helper, item);
                RelativeLayout leftMessage = helper.getView(R.id.leftMessage);
                RelativeLayout rightMessage = helper.getView(R.id.rightMessage);
                leftMessage.removeAllViews();
                rightMessage.removeAllViews();
                boolean own = item.getSenderId() == null || item.getSenderId().equals(IMManager.getInstance().getUserId());
                if (item instanceof IMTextElem) {
                    TextView textView = new TextView(MessageActivity.this);
                    IMTextElem textElem = (IMTextElem) item;
                    textView.setLayoutParams(new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                    textView.setText(textElem.getContext());
                    if (own) {
                        textView.setTextColor(getResources().getColor(android.R.color.white));
                        rightMessage.addView(textView);
                    } else {
                        textView.setTextColor(getResources().getColor(R.color.textColor2));
                        leftMessage.addView(textView);
                    }
                }

                helper.setGone(R.id.rightPanel, own)
                        .setGone(R.id.leftPanel, !own)
                        .setGone(R.id.sending, item.getSendState() == BaseElem.SEND_STATE_IN)
                        .setGone(R.id.sendError, item.getSendState() == BaseElem.SEND_STATE_NO);
            }
        };
        v.setRecyclerViewLayoutManager(R.id.recyclerView, new SmoothScrollLayoutManager(this)).setAdapter(adapter);
        adapter.setStartUpFetchPosition(2);
        mRecyclerView = v.getView(R.id.recyclerView);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        IMManager.getInstance().unRegisterMessageListener(this);
        IMManager.getInstance().unRegistermConnectState(this);
    }

    @Override
    public void update(BaseElem elem) {
        datas.add(elem);
        adapter.notifyDataSetChanged();
        mRecyclerView.smoothScrollToPosition(datas.size() - 1);
    }

    @Override
    public void sendMessageResult(int code, String identifying, String msg) {
        for (int i = 0; i < datas.size(); i++) {
            BaseElem elem = datas.get(i);
            if (elem.getIdentifying().equals(identifying)) {
                if (code == Constants.CODE_OK) {
                    elem.setSendState(BaseElem.SEND_STATE_OK);
                } else {
                    elem.setSendState(BaseElem.SEND_STATE_NO);
                    toast(msg);
                }
                adapter.notifyItemChanged(i);
            }
        }
    }


    @Override
    public void messageList(List<BaseElem> elems) {
        datas.clear();
        datas.addAll(elems);
        adapter.notifyDataSetChanged();
        mRecyclerView.scrollToPosition(datas.size() - 1);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.send_btn:
                String context = this.v.getEditText(R.id.input).getText().toString();
                if (context.length() <= 0) {
                    toast("请输入正确的内容");
                    return;
                }
                IMTextElem elem = new IMTextElem();
                elem.setAcceptorId(mUserId);
                elem.setContext(context);
                update(elem);
                MiPushClient.sendMessage(elem);
                this.v.getEditText(R.id.input).setText("");
                mRecyclerView.smoothScrollToPosition(datas.size());
                break;
        }
    }

    ViewTreeObserver.OnGlobalLayoutListener mLayoutChangeListener = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            //判断窗口可见区域大小
            Rect r = new Rect();
            // getWindowVisibleDisplayFrame()会返回窗口的可见区域高度
            getWindow().getDecorView().getWindowVisibleDisplayFrame(r);
            //如果屏幕高度和Window可见区域高度差值大于整个屏幕高度的1/3，则表示软键盘显示中，否则软键盘为隐藏状态。
            WindowManager manager = getWindowManager();
            DisplayMetrics outMetrics = new DisplayMetrics();
            manager.getDefaultDisplay().getMetrics(outMetrics);
            int height = outMetrics.heightPixels;

            int statusBarHeight1 = -1;
            //获取status_bar_height资源的ID
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                //根据资源ID获取响应的尺寸值
                statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
            }
            height = height - statusBarHeight1;
            int heightDifference = height - (r.bottom - r.top);
            boolean isKeyboardShowing = heightDifference > height / 3;
            if (isKeyboardShowing) {
//                D.i("slack","show..."+ r.bottom + " - " + r.top + " = " + (r.bottom - r.top) +","+ heightDifference);
                // bottomView 需要跟随软键盘移动的布局
                // setDuration(0) 默认300, 设置 0 ，表示动画执行时间为0，没有过程，只有动画结果了
                v.getView(R.id.input_layout).animate().translationY(-heightDifference).setDuration(0).start();
                v.getView(R.id.recyclerView).animate().translationY(-heightDifference).setDuration(0).start();
            } else {
//                D.i("slack","hide...");
                v.getView(R.id.input_layout).animate().translationY(0).start();
                v.getView(R.id.recyclerView).animate().translationY(0).start();
            }
        }
    };

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        resetHeight();
    }

    private void resetHeight() {
        v.getView(R.id.input_layout).setFocusable(true);
        v.getView(R.id.input_layout).setFocusableInTouchMode(true);
        v.getView(R.id.input_layout).requestFocus();
        /** 目前测试来看，还是挺准的
         * 原理：OnGlobalLayoutListener 每次布局变化时都会调用
         * 界面view 显示消失都会调用，软键盘显示与消失时都调用
         * */
        View mRootView = v.getView(R.id.view_latout);
        mRootView.getViewTreeObserver().addOnGlobalLayoutListener(mLayoutChangeListener);
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(v.getView(R.id.input), InputMethodManager.SHOW_IMPLICIT);
        mRootView.getViewTreeObserver().addOnGlobalLayoutListener(mLayoutChangeListener);
    }


    @Override
    public void onStateAlter(int state) {
        v.setVisible(R.id.not_connect_layout, true);
        switch (state) {
            case TCPClient.CONNECT_OK:
                v.setVisible(R.id.not_connect_layout, false);
                break;
            case TCPClient.CONNECT_IN:
                v.setText(R.id.connect_state, R.string.string9003);
                break;
            case TCPClient.CONNECT_NO:
                v.setText(R.id.connect_state, R.string.string9002);
                break;
        }
    }
}
